package com.ckv.qcm.controller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;

import com.ckv.qcm.model.*;

public class ResultController {

	private static ResultController instance;

	public static ResultController getInstance() {
		if (instance == null) {
			instance = new ResultController();
		}

		return instance;
	}
private ResultController()
{
	
}
	
	public HashMap<Long, Boolean> Check(ArrayList<Result> results) throws SQLException {
		HashMap<Long, Boolean> ret = new HashMap<Long, Boolean>();
		HashMap<Long, ArrayList<Result>> resultats = sort(results);
		
		ArrayList<Long> listQuestion= Test.findQuestionsBySession(results.get(0).getIdSession());
					for (Long idQues : listQuestion) {
						if(resultats.keySet().contains(idQues)==false)
						{
							resultats.put(idQues,new ArrayList<Result>());
						}
						
					}

		for (Long idQuestion : resultats.keySet()) {
			Boolean isGood = checkResult(resultats.get(idQuestion), idQuestion);
			ret.put(idQuestion, isGood);

		}
		return ret;
	}

	public boolean checkResult(ArrayList<Result> results, Long idQuestion) {

		Question question = Question.find(idQuestion);
		ArrayList<Answer> answers = question.getAnswers(true);

		if (answers.size() != results.size()) {
			return false;
		}

		for (Result result : results) {
			boolean t = false;
			for (Answer answer : answers) {

				if (result.getIdAnswer() == answer.getId()) {
					t = true;
				}

			}
			if (t == false) {
				return false;
			}

		}
		return true;
	}

	private HashMap<Long, ArrayList<Result>> sort(ArrayList<Result> results) {
		HashMap<Long, ArrayList<Result>> hm = new HashMap<Long, ArrayList<Result>>();

		
		for (Result result : results) {
			if (hm.containsKey(result.getIdQuestion())) {
				hm.get(result.getIdQuestion()).add(result);

			} else {
				hm.put(result.getIdQuestion(), new ArrayList<Result>());
				hm.get(result.getIdQuestion()).add(result);
			}
		}
		return hm;
	}
}
